package com.seaboxdata.scheduler;

import com.seaboxdata.entity.DataMonitorResult;
import com.seaboxdata.entity.SmsReceiverConfig;
import com.seaboxdata.service.DataMonitorResultService;
import com.seaboxdata.service.SmsReceiverConfigService;
import com.seaboxdata.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Configuration
@Slf4j
public class SmsMonitorJob {
    @Autowired
    private SmsService smsService;

    @Autowired
    private SmsReceiverConfigService smsReceiverConfigService;

    @Autowired
    private DataMonitorResultService dataMonitorResultService;

    @Value("${sms.interval}")
    private String interval;

    @Value("${isSmsMonitor}")
    private String isSmsMonitor;


    @Scheduled(cron = "${sms.DataMonitor}")
    public void doCollect() {
        //如果是sms监控,则调用,如果是数据监控部署,在空调用
        if("true".equals(isSmsMonitor)){
            log.info("==============sms监控 SmsMonitorJob start===============");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date endDate = new Date();
            Date beginDate = DateUtils.addMinutes(endDate, -Integer.valueOf(interval));
            List<DataMonitorResult> latestResults = dataMonitorResultService.getLatestResults(beginDate, endDate);
            log.info("有异常的数据：{},时间段：{}-{}",latestResults.size(),beginDate,endDate);
            if(CollectionUtils.isEmpty(latestResults)){
                //没有监控记录,发送告警短信
                List<SmsReceiverConfig> effectiveReceivers = smsReceiverConfigService.getEffectiveReceiver(endDate);
                smsService.insertDownSms(null,effectiveReceivers);
            }else{
                List<DataMonitorResult> invalidResults = new ArrayList<>();
                for (DataMonitorResult latestResult : latestResults) {
                    if("异常".equals(latestResult.getResult()) || latestResult.getTotalCount() == 0){
                        invalidResults.add(latestResult);
                    }
                }
                if(!CollectionUtils.isEmpty(invalidResults)){
                    //监控数据异常发送短信
                    List<SmsReceiverConfig> effectiveReceivers = smsReceiverConfigService.getEffectiveReceiver(endDate);
                    smsService.insertDownSms(invalidResults,effectiveReceivers);
                }
            }
            log.info("==============sms监控 SmsMonitorJob end===============");
        }
    }
}
